package com.clkj.zhonghui.service.points;

import com.clkj.zhonghui.dao.points.RebatePointsMapper;
import com.clkj.zhonghui.dao.points.RebateRelationsMapper;
import com.clkj.zhonghui.dao.points.RebateSettingsMapper;
import com.clkj.zhonghui.dao.user.UserMapper;
import com.clkj.zhonghui.pojo.common.DateFormatHelper;
import com.clkj.zhonghui.pojo.points.RebatePoints;
import com.clkj.zhonghui.pojo.points.RebateRelations;
import com.clkj.zhonghui.pojo.points.RebateSettings;
import com.clkj.zhonghui.pojo.user.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author 周佳润
 * @Date 2024/9/4 上午10:21
 */
@Service
public class PointsServiceImpl implements PointsService {
    @Autowired
    private RebateRelationsMapper rebateRelationsMapper;
    @Autowired
    private RebatePointsMapper rebatePointsMapper;
    @Autowired
    private RebateSettingsMapper rebateSettingsMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Map listPoints(Integer userId) {
        Map map =new HashMap();
        List<RebatePoints> rebatePointsList = rebatePointsMapper.listPointsFinal(userId);
        //剩余总积分
        List<RebatePoints> notExpired = rebatePointsMapper.notExpired(userId);
        List<RebatePoints> isExpired = rebatePointsMapper.isExpired(userId);
        List<RebatePoints> transferOut = rebatePointsMapper.transferOut(userId);
        double sum = notExpired.stream().mapToDouble(RebatePoints::getSurplusPoints).sum();
        map.put("remainingTotalScore",sum);//总积分
        map.put("notExpired",notExpired);//未过期
        map.put("isExpired",isExpired);//过期
        map.put("transferOut",transferOut);//赠与支付积分
        return map;
    }

    @Override
    public Map listLowerUser(Integer userId) {
        Map map =new HashMap();
        Example example = new Example(RebateRelations.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("referrerId",userId);
        List<RebateRelations> rebateRelationsList =rebateRelationsMapper.selectByExample(example);
        List<RebateRelations> rebateRelationsList1 = new ArrayList<>();
        User user = new User();
        for (RebateRelations rebateRelations : rebateRelationsList) {
            user = userMapper.selectByPrimaryKey(rebateRelations.getUserId());
            if (user != null) {
                rebateRelations.setUserName(user.getUserName());
            }
            example = new Example(RebateRelations.class);
            criteria = example.createCriteria();
            criteria.andEqualTo("referrerId",rebateRelations.getReferrerId());
            rebateRelationsList1 =rebateRelationsMapper.selectByExample(example);
            for (RebateRelations relations : rebateRelationsList1) {
                user = userMapper.selectByPrimaryKey(relations.getUserId());
                if (user != null) {
                    rebateRelations.setUserName(user.getUserName());
                }
            }
        }
        RebateRelations rebateRelations = rebateRelationsMapper.listRelations(userId);
        map.put("user",rebateRelations);
        map.put("xj",rebateRelationsList);
        map.put("xxj",rebateRelationsList1);
        return map;
    }

    @Override
    public Map listHigherUser(Integer userId) {
        Map map =new HashMap();
        RebateRelations one = new RebateRelations();
        RebateRelations two = new RebateRelations();
        RebateRelations rebateRelations = rebateRelationsMapper.listRelations(userId);
        if (rebateRelations != null) {
            one = rebateRelationsMapper.listRelations(rebateRelations.getReferrerId());
        }
        map.put("pater",one);
        if(one!=null){
            two = rebateRelationsMapper.listRelations(one.getReferrerId());
        }
        map.put("grandsire",two);
        return map;
    }

    @Override
    public void editSetting(RebateSettings rebateSettings) {
        if(rebateSettings.getSettingId().equals(null)){
            rebateSettingsMapper.insertSelective(rebateSettings);
        }else {
            RebateSettings editSettings = new RebateSettings();
            editSettings.setSettingId(rebateSettings.getSettingId());
            editSettings.setDelflag(1);
            rebateSettingsMapper.updateByPrimaryKeySelective(editSettings);
            RebateSettings rebateSettings1 = new RebateSettings();
            rebateSettings1.setLevelOnePercentage(rebateSettings.getLevelOnePercentage());
            rebateSettings1.setLevelTwoPercentage(rebateSettings.getLevelTwoPercentage());
            rebateSettings1.setUpdatedDate(DateFormatHelper.currentTimes());
            rebateSettings1.setDelflag(0);
            rebateSettingsMapper.insertSelective(rebateSettings1);
        }
    }

    @Override
    public RebateSettings listSetting() {
        Example example = new Example(RebateSettings.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("delflag", 0);
        RebateSettings rebateSettings = rebateSettingsMapper.selectOneByExample(example);
        return rebateSettings;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void increasePoints(Integer senderId, Integer receiverId, Double point) {
        String date = DateFormatHelper.currentTimes();
        RebatePoints rebatePoints = new RebatePoints();
        rebatePoints.setUserId(receiverId);//接收者
        rebatePoints.setSource(senderId);//来源发送人转增
        rebatePoints.setPoints(point);
        rebatePoints.setEarnedDate(date);
        rebatePoints.setSurplusPoints(point);
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        calendar.add(Calendar.DAY_OF_MONTH, 60);
        String expiryDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
        rebatePoints.setExpiryDate(expiryDate);
        rebatePoints.setPointType(3);//赠与获得积分

        RebatePoints rebatePoints1 = new RebatePoints();
        rebatePoints1.setUserId(senderId);//转出人
        rebatePoints1.setExportId(receiverId);//接收人
        rebatePoints1.setPoints(point);
        rebatePoints1.setEarnedDate(date);
        rebatePoints1.setPointType(2);//赠与减少积分

        Example example = new Example(RebatePoints.class);
        example.createCriteria().andEqualTo("userId",receiverId);
        RebateRelations rebateRelations = rebateRelationsMapper.selectOneByExample(example);

        if(rebateRelations==null){
            rebatePointsMapper.insertSelective(rebatePoints);//添加接收人积分详情
            rebatePointsMapper.insertSelective(rebatePoints1);//添加发送人积分详情
            RebateRelations rebateRelations1= new RebateRelations();
            rebateRelations1.setUserId(receiverId);
            rebateRelations1.setReferrerId(0);
            rebateRelations1.setNote(0);
            rebateRelationsMapper.insertSelective(rebateRelations1);
            example = new Example(RebatePoints.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", senderId);
            criteria.andIn("pointType", Arrays.asList(1, 3));
            Date currentDate = new Date();
            criteria.andGreaterThan("expiryDate", currentDate);
            example.orderBy("expiryDate").asc();
            List<RebatePoints> rebatePointsList = rebatePointsMapper.selectByExample(example);
            for (RebatePoints rebatePoint : rebatePointsList) {
                // 如果使用积分券数量大于剩余积分券数量，直接扣减，否则使用这张积分券全部积分
                if (point >= rebatePoint.getSurplusPoints()) {
                    point -= rebatePoint.getSurplusPoints(); // 更新可用积分数量
                    rebatePoint.setSurplusPoints(0.0); // 将剩余积分券数量设置为0
                    rebatePointsMapper.updateByPrimaryKeySelective(rebatePoint);
                } else if (point > 0 && rebatePoint.getSurplusPoints() > 0) {
                    double originalSurplusPoints = rebatePoint.getSurplusPoints();
                    rebatePoint.setSurplusPoints(originalSurplusPoints - point); // 更新剩余积分券数量
                    point = 0.0; // 将可用积分数量设置为0
                    rebatePointsMapper.updateByPrimaryKeySelective(rebatePoint);
                    break; // 跳出循环，因为已经没有更多的积分可以扣除了
                }
            }
        }else {
            rebatePointsMapper.insertSelective(rebatePoints);//添加接收人积分详情
            rebatePointsMapper.insertSelective(rebatePoints1);//添加发送人积分详情
            example = new Example(RebatePoints.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", senderId);
            criteria.andIn("pointType", Arrays.asList(1, 3));
            Date currentDate = new Date();
            criteria.andGreaterThan("expiryDate", currentDate);
            example.orderBy("expiryDate").asc();
            List<RebatePoints> rebatePointsList = rebatePointsMapper.selectByExample(example);
            for (RebatePoints rebatePoint : rebatePointsList) {
                // 如果使用积分券数量大于剩余积分券数量，直接扣减，否则使用这张积分券全部积分
                if (point >= rebatePoint.getSurplusPoints()) {
                    point -= rebatePoint.getSurplusPoints(); // 更新可用积分数量
                    rebatePoint.setSurplusPoints(0.0); // 将剩余积分券数量设置为0
                    rebatePointsMapper.updateByPrimaryKeySelective(rebatePoint);
                } else if (point > 0 && rebatePoint.getSurplusPoints() > 0) {
                    double originalSurplusPoints = rebatePoint.getSurplusPoints();
                    rebatePoint.setSurplusPoints(originalSurplusPoints - point); // 更新剩余积分券数量
                    point = 0.0; // 将可用积分数量设置为0
                    rebatePointsMapper.updateByPrimaryKeySelective(rebatePoint);
                    break; // 跳出循环，因为已经没有更多的积分可以扣除了
                }
            }
        }
    }

    @Override
    public List<RebatePoints> test() {
        Double num = 100.0;
        Example example = new Example(RebatePoints.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", 5);
        criteria.andIn("pointType", Arrays.asList(1, 3));
        Date currentDate = new Date();
        criteria.andGreaterThan("expiryDate", currentDate);
        example.orderBy("expiryDate").asc();
        List<RebatePoints> rebatePoints = rebatePointsMapper.selectByExample(example);
        for (RebatePoints rebatePoint : rebatePoints) {
            // 如果使用积分券数量大于剩余积分券数量，直接扣减，否则使用这张积分券全部积分
            if (num >= rebatePoint.getSurplusPoints()) {
                num -= rebatePoint.getSurplusPoints(); // 更新可用积分数量
                rebatePoint.setSurplusPoints(0.0); // 将剩余积分券数量设置为0
                rebatePointsMapper.updateByPrimaryKeySelective(rebatePoint);
            } else if (num > 0 && rebatePoint.getSurplusPoints() > 0) {
                double originalSurplusPoints = rebatePoint.getSurplusPoints();
                rebatePoint.setSurplusPoints(originalSurplusPoints - num); // 更新剩余积分券数量
                num = 0.0; // 将可用积分数量设置为0
                rebatePointsMapper.updateByPrimaryKeySelective(rebatePoint);
                break; // 跳出循环，因为已经没有更多的积分可以扣除了
            }
        }
        return rebatePoints;
    }

}
